package mylab.io.base.sync;

import com.google.common.util.concurrent.SettableFuture;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

import lombok.EqualsAndHashCode;
import lombok.Getter;
import mylab.io.base.model.Msg;

/**
 * 配对的请求与应答
 */
@Getter
@EqualsAndHashCode(onlyExplicitlyIncluded = true, callSuper = false)
public class Couple {

    @EqualsAndHashCode.Include
    private final String code;

    private final Msg request;
    private final SettableFuture<Msg> responseFuture;

    public Couple(Msg request) {
        this.code = request.getCode();
        this.request = request;
        this.responseFuture = SettableFuture.create();
    }

    public Msg getResponse(long timeout, TimeUnit unit) throws Exception {
        try {
            return responseFuture.get(timeout, unit);
        } catch (TimeoutException timeoutException) {
            throw new TimeoutException(String.format("接收同步应答超时。当前超时设置值：%s %s", timeout, unit));
        }

    }

}
